<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" draggable :close-on-click-modal="false" width="640px">
			<el-form ref="roleDialogFormRef" :model="state.roleForm" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色名称" prop="name" :rules="[{required:true,message:'角色名称不能为空',trigger:'blur'}]">
							<el-input v-model="state.roleForm.name" placeholder="请输入角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色权限" prop="code" :rules="[{ required: true, message: '角色编码不能为空', trigger: 'blur' }]">
							<el-input v-model="state.roleForm.code" placeholder="角色编码" clearable :disabled="state.roleForm.code == 'sysadmin' && state.roleForm.id != undefined" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序">
							<el-input-number v-model="state.roleForm.orderNo" :min="0" :max="999" controls-position="right" placeholder="请输入排序" class="w100" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态">
							<el-radio-group v-model="state.roleForm.status">
								<el-radio :label="1">启用</el-radio>
								<el-radio :label="2">禁用</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色描述">
							<el-input v-model="state.roleForm.remarks" clearable type="textarea" placeholder="请输入角色描述" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单权限">
							<el-tree :data="state.menuData" :props="state.menuProps" show-checkbox class="menu-data-tree" />
						</el-form-item>
					</el-col> -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单权限" v-loading="state.loading">
							<el-tree
								ref="treeRef"
								:data="state.menuData"
								node-key="id"
								show-checkbox
								:props="{ children: 'children', label: 'title', class: treeNodeClass }"
								icon="ele-Menu"
								highlight-current
								default-expand-all
							/>
						</el-form-item>
					</el-col>

				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRoleDialog">
import { ElMessage,ElTree } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useMenuApi } from '/@/api/menu';
import { useRoleApi } from '/@/api/role';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
// 定义变量内容
const roleDialogFormRef = ref();
const treeRef = ref<InstanceType<typeof ElTree>>();
const state = reactive({
	roleForm: {} as RoleForm,
	menuData: [] as Array<MenuForm>,
	// menuProps: {
	// 	children: 'children',
	// 	label: 'label',
	// },
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});
onMounted(async () => {
	state.loading = true;
	getMenuData();
	state.loading = false;
});

// 打开弹窗
const openDialog = (type: string, row: RoleForm) => {
	console.log('type:'+type);
	treeRef.value?.setCheckedKeys([]); // 清空选中值
	if (type === 'edit') {
		state.roleForm = row;
		state.dialog.title = '修改角色';
		state.dialog.submitTxt = '修 改';
		//console.log(JSON.stringify(row)+'|'+row.id);
		if (row.id != undefined&&row.id>0) {
			useRoleApi().getRoleMenuIds({id:row.id}).then(async(res:AjaxResult)=>{
				treeRef.value?.setCheckedKeys(res.data ?? []);
			});
		}
	} else {
		state.roleForm = row;
		state.dialog.title = '新增角色';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
		// nextTick(() => {
		// 	roleDialogFormRef.value.resetFields();
		// });
		// var res = await getAPI(SysRoleApi).apiSysRoleOwnMenuListGet(row.id);
		// setTimeout(() => {
		// 	treeRef.value?.setCheckedKeys(res.data.result ?? []);
		// }, 100);
	}
	state.dialog.isShowDialog = true;
	//getMenuData();
};
// 关闭弹窗
const closeDialog = () => {
	emit('refresh');
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	// closeDialog();
	// emit('refresh');
	roleDialogFormRef.value.validate(async (valid: boolean) => {
		if (!valid) return;
		state.roleForm.menuIdList = treeRef.value?.getCheckedKeys() as Array<number>;
		if (state.roleForm.id != undefined && state.roleForm.id > 0) {
			useRoleApi().editRole(state.roleForm).then(async (res: AjaxResult) => {
				if (res.success == true) {
					ElMessage.success('更新成功');
					emit('refresh');
					closeDialog();
				}
				else {
					ElMessage.warning('更新失败：' + res.message);
				}
			});
		} else {
			useRoleApi().addRole(state.roleForm).then(async (res: AjaxResult) => {
				if (res.success == true) {
					ElMessage.success('新增成功');
					emit('refresh');
					closeDialog();
				}
				else {
					ElMessage.warning('新增失败：' + res.message);
				}
			});
		}
		//closeDialog();
	});
};
// 获取菜单结构数据
const getMenuData = () => {
	useMenuApi().getMenuList().then(async (res: AjaxResult)=>{
		const _data : Array<MenuForm> = res.data;
		state.menuData = _data;
	});

	// state.menuData = [
	// 	{
	// 		id: 1,
	// 		label: '系统管理',
	// 		children: [
	// 			{
	// 				id: 11,
	// 				label: '菜单管理',
	// 				children: [
	// 					{
	// 						id: 111,
	// 						label: '菜单新增',
	// 					},
	// 					{
	// 						id: 112,
	// 						label: '菜单修改',
	// 					},
	// 					{
	// 						id: 113,
	// 						label: '菜单删除',
	// 					},
	// 					{
	// 						id: 114,
	// 						label: '菜单查询',
	// 					},
	// 				],
	// 			},
	// 			{
	// 				id: 12,
	// 				label: '角色管理',
	// 				children: [
	// 					{
	// 						id: 121,
	// 						label: '角色新增',
	// 					},
	// 					{
	// 						id: 122,
	// 						label: '角色修改',
	// 					},
	// 					{
	// 						id: 123,
	// 						label: '角色删除',
	// 					},
	// 					{
	// 						id: 124,
	// 						label: '角色查询',
	// 					},
	// 				],
	// 			},
	// 			{
	// 				id: 13,
	// 				label: '用户管理',
	// 				children: [
	// 					{
	// 						id: 131,
	// 						label: '用户新增',
	// 					},
	// 					{
	// 						id: 132,
	// 						label: '用户修改',
	// 					},
	// 					{
	// 						id: 133,
	// 						label: '用户删除',
	// 					},
	// 					{
	// 						id: 134,
	// 						label: '用户查询',
	// 					},
	// 				],
	// 			},
	// 		],
	// 	},
	// 	{
	// 		id: 2,
	// 		label: '权限管理',
	// 		children: [
	// 			{
	// 				id: 21,
	// 				label: '前端控制',
	// 				children: [
	// 					{
	// 						id: 211,
	// 						label: '页面权限',
	// 					},
	// 					{
	// 						id: 212,
	// 						label: '页面权限',
	// 					},
	// 				],
	// 			},
	// 			{
	// 				id: 22,
	// 				label: '后端控制',
	// 				children: [
	// 					{
	// 						id: 221,
	// 						label: '页面权限',
	// 					},
	// 				],
	// 			},
	// 		],
	// 	},
	// ];
};
// 叶子节点同行显示样式
const treeNodeClass = (node: MenuForm) => {
	let addClass = true; // 添加叶子节点同行显示样式
	for (var key in node.children) {
		// 如果存在子节点非叶子节点，不添加样式
		if (node.children[key].children?.length ?? 0 > 0) {
			addClass = false;
			break;
		}
	}
	return addClass ? 'penultimate-node' : '';
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-role-dialog-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
}
</style>
